<?php

//mysqli数据库基类

class dbMysqli {
    
    public $link;    
    public $lastID = 0;
    public $affRows = 0;
    public $dbName = '';
    public $config = array();
    
    // 初始化,是否支持mysqli
    function __construct(){
        if(!function_exists('mysqli_connect')){ 
            abort('Function `mysqli_connect` NOT Found.', 602); 
        }
    }
    //连接数据库
    function connect($config=array()){
        $this->dbName = $config['db_name'];
        $this->config = $config; 
        $this->link = @mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name'], $config['db_port']);
        if(!$this->link) {
            abort('Connect(mysqli_connect) to Mysql Error!', 602); 
        }
        mysqli_query($this->link, "SET character_set_connection=".$config['db_cset'].", character_set_results=".$config['db_cset'].", character_set_client=binary");
    }
    
    // select, 0-arr, 1-row, 2-val
    function get($sql, $mode=0){
        $res = $this->query($sql);
        if($mode){ // MYSQL_NUM(2) : MYSQL_ASSOC(1) :MYSQL_BOTH(3) 
            $row = mysqli_fetch_array($res, $mode); 
            return $mode==2 ? (empty($row[0]) ? '' : $row[0]) : (empty($row) ? [] : $row);
        }else{
            $data = array();
            while($row=mysqli_fetch_array($res, 1)) $data[]=$row;
            return $data;
        }
    }
    function query($sql){ 
        $res = mysqli_query($this->link, $sql);
        if(!$res){
            abort(mysqli_error($this->link), mysqli_errno($this->link)); // , 602
        }
        return $res;
    }
    // 执行语句(update, delete insert, other)
    function run($sql){ 
        $res = $this->query($sql);
        $this->affRows = mysqli_affected_rows($this->link); $this->lastID = '';
        if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $sql)) {
            $this->lastID = ($id = mysqli_insert_id($this->link)) >= 0 ? $id : 0;
        }
        return ['lastId'=>$this->lastID, 'affRows'=>$this->affRows];
    }
      
    //返回quoteSql语句
    function quoteSql($sql){
        return mysqli_real_escape_string($this->link, $sql);
    }

    //释放结果内存
    function free($query) {
        return mysqli_free_result($query);
    }

    function close(){
        if($this->link) @mysqli_close($this->link);
    }
    function __destruct(){
        $this->close();
    }

}
